package cn.yuanqiao.web.controller.archive.quanzongjuanguanli;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.archive.quanzongjuanguanli.domain.YqQzjjsHb;
import cn.yuanqiao.archive.utils.ImageUtils;
import cn.yuanqiao.archive.utils.WordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.archive.quanzongjuanguanli.service.IYqQzjjsService;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.web.page.TableDataInfo;
import org.apache.commons.lang3.StringUtils;
import java.awt.image.BufferedImage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.lang.reflect.Modifier;

/**
 * 全宗卷介绍Controller
 * 
 * @author sy
 * @date 2023-09-20
 */
@RestController
@RequestMapping("/archive/yqQzjjs")
public class YqQzjjsController extends BaseController
{
    @Autowired
    private IYqQzjjsService yqQzjjsService;
    /**
     * 查询全宗卷介绍列表
     */
//    @PreAuthorize("@ss.hasPermi('archive:yqQzjjs:list')")
    @GetMapping("/list")
    public TableDataInfo list(YqQzjjsHb yqQzjjsHb)
    {
        startPage();
        List<YqQzjjsHb> list = yqQzjjsService.selectYqQzjjsList(yqQzjjsHb);
        return getDataTable(list);
    }

    /**
     * 导出全宗卷介绍列表
     */
//    @PreAuthorize("@ss.hasPermi('archive:yqQzjjs:export')")
    @Log(title = "全宗卷介绍", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response, YqQzjjsHb yqQzjjsHb)
    {
        if (null==yqQzjjsHb.getId()){
            //新增
            yqQzjjsService.insertYqQzjjs(yqQzjjsHb);
        }else {
            //修改
            yqQzjjsService.updateYqQzjjs(yqQzjjsHb);
        }
//        List<YqQzjjsHb> list = new ArrayList<>();
//        list.add(yqQzjjsHb);
////        List<YqQzjjsHb> list = yqQzjjsService.selectYqQzjjsList(yqQzjjsHb);
//        ExcelUtil<YqQzjjsHb> util = new ExcelUtil<YqQzjjsHb>(YqQzjjsHb.class);
//        util.exportExcel(response, list, "全宗卷介绍数据");

        try {
//            String tmpContent = "<h1>如何将富文本内容导出到word文档</h1><p style=\"color:red;font-size:20px;\">采用poi将富文本内容导出到word文档</p><div style=\"background-color:green;\">这是有背景颜色的div内容</div>\n" +
//                    "<img src=\"这里写base64后的图片编码\">这是base64编码后的图片";
            String tmpContent = WordUtil.montageYqQzjjsHb(yqQzjjsHb);
            tmpContent = tmpContent.replaceAll("class=\"ql-align-center\"", "style=\"text-align: center\"");


            // 获取img图片标签
            // 1.Jsoup解析html
            Document document = Jsoup.parse(tmpContent);
            // 获取所有img图片标签
            Elements img = document.getElementsByTag("img");
            int index = 0;
            List<String> imgBase64List = new ArrayList<>();
            for (Element element : img) {
//                byte[] imageBytes = ImageUtils.downloadImage(element.attr("src"));
//                String attrData = Base64.getEncoder().encodeToString(imageBytes);
                imgBase64List.add(element.attr("src"));
                // 处理特殊符号
                String attrData = element.attr("src");
                // base64编码后可能包含 + 特殊字符,所以需要转义
                attrData = attrData.replaceAll("\\+", "\\\\+");
                tmpContent = tmpContent.replaceAll(attrData, "{{image_src" + index + "}}");
                index++;
            }
            // 缩放图片大小,然后重新base64编码后替换到富文本内容里面导出word
            index = 0;
            String prefix = "data:image/png;base64,"; // base64编码前缀
            for (String base64 : imgBase64List) {
                if (StringUtils.isNotBlank(base64)) {
                    byte[] imageBytes = ImageUtils.downloadImage(base64);
                    base64 = Base64.getEncoder().encodeToString(imageBytes);
                    // 缩小图片
                    base64 = base64.replaceAll(prefix, "");
                    BufferedImage bufferedImage = ImageUtils.bytesToBufferedImage(ImageUtils.base64ToByte(base64));
                    if (bufferedImage == null) {
                        tmpContent = tmpContent.replaceAll("\\{\\{image_src" + index + "}}", "");
                    } else {
                        int height = bufferedImage.getHeight();
                        int width = bufferedImage.getWidth();
                        // 如果图片宽度大于650,图片缩放
                        //System.out.println("----"+width+"-----"+height);
                        if (width > 650) {
                            //高度等比缩放
                            height = (int)(height*650.0/width);
                            BufferedImage imgZoom = ImageUtils.resizeImage(bufferedImage, 700, height);
                            String imageToBase64 = ImageUtils.imageToBase64(ImageUtils.imageToBytes(imgZoom));
                            tmpContent = tmpContent.replaceAll("\\{\\{image_src" + index + "}}", prefix + imageToBase64);
                        } else {
                            tmpContent = tmpContent.replaceAll("\\{\\{image_src" + index + "}}", prefix + base64);
                        }
                    }
                } else {
                    tmpContent = tmpContent.replaceAll("\\{\\{image_src" + index + "}}", "");
                }
                index++;
            }
            // 执行导出操作
            WordUtil.exportHtmlToWord(request, response, tmpContent, "全宗卷介绍导出word");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取全宗卷介绍详细信息
     */
//    @PreAuthorize("@ss.hasPermi('archive:yqQzjjs:query')")
    @GetMapping(value = "/{fondsId}")
    public AjaxResult getInfoByFondsId(@PathVariable("fondsId") String fondsId)
    {
        return success(yqQzjjsService.selectYqQzjjsByFondsId(fondsId));
    }

//    /**
//     * 新增全宗卷介绍
//     */
////    @PreAuthorize("@ss.hasPermi('archive:yqQzjjs:add')")
//    @Log(title = "全宗卷介绍", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody YqQzjjs yqQzjjs)
//    {
//        return toAjax(yqQzjjsService.insertYqQzjjs(yqQzjjs));
//    }

    /**
     * 新增全宗卷介绍
     */
//    @PreAuthorize("@ss.hasPermi('archive:yqQzjjs:add')")
    @Log(title = "全宗卷介绍", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YqQzjjsHb yqQzjjsHb)
    {
        try {
//            yqQzjjsHb.setRole(URLDecoder.decode(yqQzjjsHb.getRole(), StandardCharsets.UTF_8.toString()));
//            yqQzjjsHb.setDirectorList(URLDecoder.decode(yqQzjjsHb.getDirectorList(), StandardCharsets.UTF_8.toString()));
//            yqQzjjsHb.setOrganization(URLDecoder.decode(yqQzjjsHb.getOrganization(), StandardCharsets.UTF_8.toString()));
//            yqQzjjsHb.setCompleteness(URLDecoder.decode(yqQzjjsHb.getCompleteness(), StandardCharsets.UTF_8.toString()));
//            yqQzjjsHb.setAppraisalSituation(URLDecoder.decode(yqQzjjsHb.getAppraisalSituation(), StandardCharsets.UTF_8.toString()));
//            yqQzjjsHb.setSearchTool(URLDecoder.decode(yqQzjjsHb.getSearchTool(), StandardCharsets.UTF_8.toString()));
            Field[] fields = yqQzjjsHb.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                int modifiers = field.getModifiers();
                if (!Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers)) {
                    Object value = field.get(yqQzjjsHb);
                    if (value != null && value instanceof String) {
                        try {
                            String decodedValue = URLDecoder.decode(value.toString(), "UTF-8");
                            field.set(yqQzjjsHb, decodedValue);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                            // 处理解码异常，例如打印错误信息或执行其他逻辑
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(yqQzjjsService.insertYqQzjjs(yqQzjjsHb));
    }

//    /**
//     * 修改全宗卷介绍
//     */
////    @PreAuthorize("@ss.hasPermi('archive:yqQzjjs:edit')")
//    @Log(title = "全宗卷介绍", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody YqQzjjs yqQzjjs)
//    {
//        return toAjax(yqQzjjsService.updateYqQzjjs(yqQzjjs));
//    }

    /**
     * 修改全宗卷介绍
     */
//    @PreAuthorize("@ss.hasPermi('archive:yqQzjjs:edit')")
    @Log(title = "全宗卷介绍", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YqQzjjsHb yqQzjjsHb) {
        try {
//            yqQzjjsHb.setRole(URLDecoder.decode(yqQzjjsHb.getRole(), StandardCharsets.UTF_8.toString()));
//            yqQzjjsHb.setDirectorList(URLDecoder.decode(yqQzjjsHb.getDirectorList(), StandardCharsets.UTF_8.toString()));
//            yqQzjjsHb.setOrganization(URLDecoder.decode(yqQzjjsHb.getOrganization(), StandardCharsets.UTF_8.toString()));
//            yqQzjjsHb.setCompleteness(URLDecoder.decode(yqQzjjsHb.getCompleteness(), StandardCharsets.UTF_8.toString()));
//            yqQzjjsHb.setAppraisalSituation(URLDecoder.decode(yqQzjjsHb.getAppraisalSituation(), StandardCharsets.UTF_8.toString()));
//            yqQzjjsHb.setSearchTool(URLDecoder.decode(yqQzjjsHb.getSearchTool(), StandardCharsets.UTF_8.toString()));
            Field[] fields = yqQzjjsHb.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                int modifiers = field.getModifiers();
                if (!Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers)) {
                    Object value = field.get(yqQzjjsHb);
                    if (value != null && value instanceof String) {
                        try {
                            String decodedValue = URLDecoder.decode(value.toString(), "UTF-8");
                            field.set(yqQzjjsHb, decodedValue);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                            // 处理解码异常，例如打印错误信息或执行其他逻辑
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(yqQzjjsService.updateYqQzjjs(yqQzjjsHb));
    }

    /**
     * 删除全宗卷介绍
     */
//    @PreAuthorize("@ss.hasPermi('archive:yqQzjjs:remove')")
    @Log(title = "全宗卷介绍", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(yqQzjjsService.deleteYqQzjjsByIds(ids));
    }
}
